package com.testing.class13;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.testing.common.AutoTools;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @Classname JsonRegisterTest
 * @Description 类型说明
 * @Date 2022/11/2 20:10
 * @Created by 特斯汀Roy
 */
public class JsonRegisterTest {
    public static CloseableHttpClient aDefault = HttpClients.createDefault();

    public static void main(String[] args) throws IOException {
        //完成请求操作，得到返回结果
        String register = postJson("http://localhost:9090/user/register", "{\"username\":\"roy" + AutoTools.dateStr("mmss") + "\",\"password\":\"123456\",\"nickname\":\"roy老师\",\"describe\":\"asdf1阿斯蒂芬\"}");
        //对返回结果进行断言
        assertJsonValue(register,"注册成功","$.msg");
        String login = postJson("http://www.testingedu.com.cn/mypro/api/user/login", "{\"username\":\"roy\",\"pwd\":\"123456\"}");
        assertJsonValue(login,"roy老师呀","$.data[0].nickname");
    }


    /**
     *
     * @param url
     * @param param
     * @return
     * @throws IOException
     */
    public static String postJson(String url,String param) throws IOException {
        HttpPost register=new HttpPost(url);
        //请求体
        StringEntity registerParam=new StringEntity(param,"utf-8");
        registerParam.setContentType("application/json");
        register.setEntity(registerParam);

        String result = EntityUtils.toString(aDefault.execute(register).getEntity(), "utf-8");
        AutoTools.log.info(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        AutoTools.log.info("输出的fastjson处理之后的对象是："+jsonObject.toJSONString());
        return result;
    }


    public static boolean assertJsonValue(String result,String expectedResult,String jsonPath){
        String actual = JSONPath.read(result, jsonPath).toString();
        if (expectedResult.equals(actual)){
            AutoTools.log.info("测试成功实际值是:"+actual);
            return true;
        }else{
            AutoTools.log.error("测试失败实际值是"+actual);
            return false;
        }
    }
}
